package com.haibei.view;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.MainActivity;
import com.haibei.activity.consult.ConsultDetailActivity;
import com.haibei.adapter.ArticleAdapter;
import com.haibei.adapter.bean.Article;
import com.haibei.adapter.bean.ArticleCategory;
import com.haibei.adapter.bean.MenuItem;
import com.haibei.net.NetInterface;
import com.haibei.view.PullToRefreshView.OnFooterRefreshListener;
import com.haibei.view.PullToRefreshView.OnHeaderRefreshListener;

/**
 * 咨询页面
 * 
 * @author wangzy
 */
public class SubTabViewArticle extends SubTabView implements View.OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {

	private ImageButton imageButtonSlideMenu;
	private OnSlideButtonClickListener onSlideButtonClickListener;
	private ArrayList<Article> mArrayList;
	private ListView mListViewConsults;
	private ArticleAdapter mAdapterConsult;
	private Handler mHandler;
	private BaseTask mBaseTask;
	private MainActivity mainActivity;
	private final int page_size = 10;
	private final int INT_RTYPE_FIRST = 1;
	private final int INT_RTYPE_REFRESH = 2;
	private final int INT_RTYPE_LODMORE = 3;
	public static String categoryId = String.valueOf((MenuItem.CATE_HEADER_ID));// 默认选择头条
	public static ArticleCategory defaultCate = null;
	public Article mArticleCurrent;
	private PullToRefreshView mPullToRefreshView;

	public SubTabViewArticle(MainActivity activity) {
		super(activity);
		this.mainActivity = activity;
		mArrayList = new ArrayList<Article>();
	}

	@Override
	public void initView() {
		this.mContentView = View.inflate(mActivity, R.layout.sub_tab_consult, null);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		this.mListViewConsults = (ListView) findViewById(R.id.listViewConsults);
		mHandler = new Handler();
		imageButtonSlideMenu = (ImageButton) findViewById(R.id.imageButtonSlideMenu);
		imageButtonSlideMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null != onSlideButtonClickListener) {
					onSlideButtonClickListener.OnSlideClick();
				}
			}
		});
	}

	@Override
	public void onShow() {
		getActivity().getSlidingMenu().setSlidingEnabled(true);
		if (!ListUtiles.isEmpty(mArrayList)) {
			return;
		} else {
			requestFirst();
		}

	}

	public static void setCategory(MenuItem mi) {
		categoryId = mi.getmArticleCategory().getId();
	}

	public void requestFirst() {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", "0");
		hmap.put("limit", String.valueOf(page_size));
		hmap.put("categoryId", categoryId);
		getRequestTask(INT_RTYPE_FIRST).execute(hmap);

	}

	private void refreshList(int type) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", "0");
		hmap.put("limit", String.valueOf(page_size));
		hmap.put("categoryId", categoryId);
		getRequestTask(type).execute(hmap);
	}

	private void refreshList(int offset, int limit, int type) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", String.valueOf(offset));
		hmap.put("limit", String.valueOf(limit));
		hmap.put("categoryId", categoryId);
		getRequestTask(type).execute(hmap);
	}

	// 请求头条
	public BaseTask getRequestTask(final int type) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onCanCell() {
				LogUtil.i(App.tag, "caoncell......");
			}

			@Override
			public void onPreCall() {
				if (type == 1) {
					mActivity.showProgressDialogWithTask(mBaseTask);
				}
			}

			@Override
			public void onFinish(NetResult result) {
				if (type == 1) {
					mActivity.hideProgressDialogWithTask();
				}
				if (null != result) {
					if (result.isSuccess()) {
						ArrayList<Article> ret = (ArrayList<Article>) result.getData()[0];
						buildConsultAdapter(ret, type);
					} else {
						Tool.ToastShow(mActivity, result.getMessage());
					}
				} else {
					showRetryDailog(type, getActivity().getResources().getString(R.string.error_net), true);// 展示重试
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					if (categoryId.equals(String.valueOf(MenuItem.CATE_HEADER_ID))) {// 如果是头条
						netResult = NetInterface.getHeaderArticle(mActivity, paramMap);
					} else {
						netResult = NetInterface.getArticle(mActivity, paramMap);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	// 展示重试对话框
	private void showRetryDailog(final int type, String message, boolean isEnableCancell) {
		final Dialog dialog = new Dialog(getActivity(), R.style.Translucent_NoTitle);
		dialog.setCancelable(isEnableCancell);
		View viewWaring = View.inflate(getActivity(), R.layout.dialog_retry, null);
		TextView textViewTitle = (TextView) viewWaring.findViewById(R.id.textViewTitle);
		textViewTitle.setText(message);
		Button btnRetry = (Button) viewWaring.findViewById(R.id.buttonRetry);
		btnRetry.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (type) {
				case INT_RTYPE_FIRST:
					requestFirst();
					break;
				case INT_RTYPE_REFRESH:
					refreshList(INT_RTYPE_REFRESH);
					break;
				case INT_RTYPE_LODMORE:
					refreshList(mArrayList.size(), page_size, INT_RTYPE_LODMORE);
					break;
				}
				dialog.dismiss();
			}
		});
		Button btnCalcell = (Button) viewWaring.findViewById(R.id.buttonCancell);
		btnCalcell.setEnabled(isEnableCancell);
		btnCalcell.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.setContentView(viewWaring);
		dialog.show();
	}

	/**
	 * 更新列表数据
	 * 
	 * @param datas
	 * @param rtype
	 */
	private void buildConsultAdapter(ArrayList<Article> datas, int rtype) {
		LogUtil.i(App.tag, "msg tag...." + rtype);
		switch (rtype) {
		case INT_RTYPE_FIRST:
			// 首次请求
			mArrayList.clear();// 数据清零
			LogUtil.i(App.tag, "首次请求加载:" + datas.size());
			mArrayList.addAll(datas);
			mAdapterConsult = new ArticleAdapter(getActivity(), mArrayList);
			mListViewConsults.setAdapter(mAdapterConsult);
			break;
		case INT_RTYPE_REFRESH:
			mArrayList.clear();// 数据清零
			mArrayList.addAll(datas);
			mAdapterConsult = new ArticleAdapter(getActivity(), mArrayList);
			mListViewConsults.setAdapter(mAdapterConsult);
			mAdapterConsult.notifyDataSetChanged();
			break;
		case INT_RTYPE_LODMORE:
			LogUtil.i(App.tag, "更多请求加载:" + datas.size() + "原来：" + mArrayList.size());
			mArrayList.addAll(datas);
			mAdapterConsult.notifyDataSetChanged();
			break;
		default:
			break;
		}
		showEmpty(mAdapterConsult);
		mListViewConsults.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
				goToDetail(mArrayList.get(pos));
			}
		});
	}

	public void showEmpty(Adapter ada) {
		int visibility = ((null == ada) || ada.getCount() == 0 ? View.VISIBLE : View.GONE);
		findViewById(R.id.textViewEmpty).setVisibility(visibility);
	}

	public void hideEmpty() {
		findViewById(R.id.textViewEmpty).setVisibility(View.GONE);
	}

	public OnSlideButtonClickListener getOnSlideButtonClickListener() {
		return onSlideButtonClickListener;
	}

	public void setOnSlideButtonClickListener(OnSlideButtonClickListener onSlideButtonClickListener) {
		this.onSlideButtonClickListener = onSlideButtonClickListener;
	}

	public static interface OnSlideButtonClickListener {
		public void OnSlideClick();
	}

	@Override
	public void onClick(View v) {
	}

	private void goToDetail(Article article) {
		mArticleCurrent = article;
		Intent i = new Intent();
		i.putExtra("article", article);
		i.setClass(getActivity(), ConsultDetailActivity.class);
		getActivity().startActivity(i);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				refreshList(mArrayList.size(), page_size, INT_RTYPE_LODMORE);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				refreshList(INT_RTYPE_REFRESH);
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);
	}
}
